package com.huangsm.book.designmodel;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Cglib动态代理
 * @author huang
 * @PACKAGE_NAME com.huangsm.book.designmodel
 * @PROJECT_NAME concurrence
 * @date 2019/2/15
 */
public class CglibDbQueryProxy implements MethodInterceptor {
    IDKQuery  real=null;
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if (real==null){
            real=new DBQuery();
        }
        return real.request();
    }
    public static IDKQuery createCglibProxy(){
        Enhancer enhancer = new Enhancer();
        //指定切入器，定义代理类逻辑
        enhancer.setCallback(new CglibDbQueryProxy());
        //指定实现接口
        enhancer.setInterfaces(new Class[]{IDKQuery.class});
        //生成代理类
        IDKQuery cglibProxy = (IDKQuery) enhancer.create();
        return cglibProxy;
    }
}
